import axios from 'axios'
import router from '@/router'
const timeout = 60000 * 10
import { userStore } from '@/stores/user'
const instance = axios.create({
  baseURL: '/mock',
  timeout
})
const nodeService = axios.create({
  baseURL: '/math/score',
  timeout
})
const customerService = axios.create({
  baseURL: '/math/customer',
  timeout
})
const loginService = axios.create({
  baseURL: '/math/server',
  timeout
})
const mathService = axios.create({
  baseURL: '/math',
  timeout
})
// 请求拦截
// 添加请求拦截器
const services = [instance, nodeService, loginService, customerService, mathService]
const store = userStore()
services.forEach((instance) => {
  // 在发送请求拦截
  instance.interceptors.request.use((config) => {
    if (store.token) {
      config.headers['Authorization'] = store.token
    }
    return config
  }, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  })
  // 响应拦截
  instance.interceptors.response.use((response) => {
    return response.data
  }, (error) => {
    if (error.response.status === 401) {
      router.push('/login')
      // @ts-ignore
      store.setUserInfo('', '', '')
    } else {
      return Promise.reject(error)
    }
  })
})
export { nodeService, loginService, customerService, mathService }
export default instance
